#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
HTTP客户端基本使用示例

该示例展示了HTTP客户端模块的基本用法，包括发送各种HTTP请求、处理响应等。

创建时间: 2023-07-15
作者: Python Tools Team
"""

import os
import sys

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../..')))

from modules.http_client import HttpClient, HttpMethod, RequestBuilder
from modules.http_client.exception import HttpClientException
from modules.logger import LogManager

# 创建日志记录器
logger = LogManager.get_console_logger(name="http_client_example")


def basic_requests_example():
    """
    基本HTTP请求示例
    """
    logger.info("=== 基本HTTP请求示例 ===")
    
    # 创建HTTP客户端
    client = HttpClient(
        base_url="https://httpbin.org",
        headers={"User-Agent": "Python-Tools-HttpClient/1.0"}
    )
    
    try:
        # GET请求
        logger.info("发送GET请求...")
        response = client.get("/get", params={"param1": "value1", "param2": "value2"})
        logger.info(f"GET响应状态码: {response.status_code}")
        logger.info(f"GET响应内容: {response.json()}")
        
        # POST请求 - 表单数据
        logger.info("\n发送POST请求(表单数据)...")
        response = client.post(
            "/post", 
            data={"field1": "value1", "field2": "value2"},
            headers={"Content-Type": "application/x-www-form-urlencoded"}
        )
        logger.info(f"POST响应状态码: {response.status_code}")
        logger.info(f"POST响应内容: {response.json()}")
        
        # POST请求 - JSON数据
        logger.info("\n发送POST请求(JSON数据)...")
        response = client.post(
            "/post", 
            json_data={"field1": "value1", "field2": "value2"}
        )
        logger.info(f"POST响应状态码: {response.status_code}")
        logger.info(f"POST响应内容: {response.json()}")
        
        # PUT请求
        logger.info("\n发送PUT请求...")
        response = client.put(
            "/put", 
            json_data={"field1": "updated_value"}
        )
        logger.info(f"PUT响应状态码: {response.status_code}")
        logger.info(f"PUT响应内容: {response.json()}")
        
        # DELETE请求
        logger.info("\n发送DELETE请求...")
        response = client.delete("/delete")
        logger.info(f"DELETE响应状态码: {response.status_code}")
        logger.info(f"DELETE响应内容: {response.json()}")
        
        # PATCH请求
        logger.info("\n发送PATCH请求...")
        response = client.patch(
            "/patch", 
            json_data={"field1": "patched_value"}
        )
        logger.info(f"PATCH响应状态码: {response.status_code}")
        logger.info(f"PATCH响应内容: {response.json()}")
        
    except HttpClientException as e:
        logger.error(f"HTTP请求异常: {e.message}")
        logger.error(f"异常详情: {e.details}")
    finally:
        # 关闭客户端
        client.close()


def request_builder_example():
    """
    请求构建器示例
    """
    logger.info("\n=== 请求构建器示例 ===")
    
    # 创建HTTP客户端
    client = HttpClient(base_url="https://httpbin.org")
    
    try:
        # 使用请求构建器构建和发送请求
        logger.info("使用请求构建器发送GET请求...")
        builder = RequestBuilder(client)
        response = builder.url("/get") \
                          .param("param1", "value1") \
                          .param("param2", "value2") \
                          .header("X-Custom-Header", "custom-value") \
                          .timeout(10.0) \
                          .get()
        
        logger.info(f"GET响应状态码: {response.status_code}")
        logger.info(f"GET响应内容: {response.json()}")
        
        # 使用请求构建器发送POST请求
        logger.info("\n使用请求构建器发送POST请求...")
        response = builder.url("/post") \
                          .json({"field1": "value1", "field2": "value2"}) \
                          .post()
        
        logger.info(f"POST响应状态码: {response.status_code}")
        logger.info(f"POST响应内容: {response.json()}")
        
    except HttpClientException as e:
        logger.error(f"HTTP请求异常: {e.message}")
        logger.error(f"异常详情: {e.details}")
    finally:
        # 关闭客户端
        client.close()


def error_handling_example():
    """
    错误处理示例
    """
    logger.info("\n=== 错误处理示例 ===")
    
    # 创建HTTP客户端
    client = HttpClient(base_url="https://httpbin.org")
    
    try:
        # 请求不存在的URL
        logger.info("请求不存在的URL...")
        response = client.get("/status/404")
        
        # 检查响应状态
        if response.is_success():
            logger.info("请求成功")
        elif response.is_client_error():
            logger.warning(f"客户端错误: {response.status_code}")
        elif response.is_server_error():
            logger.warning(f"服务器错误: {response.status_code}")
        
        # 使用raise_for_status抛出异常
        logger.info("\n使用raise_for_status抛出异常...")
        try:
            response.raise_for_status()
        except HttpClientException as e:
            logger.error(f"HTTP响应异常: {e.message}")
            logger.error(f"异常详情: {e.details}")
        
        # 请求超时
        logger.info("\n模拟请求超时...")
        try:
            client.get("/delay/10", timeout=1.0)
        except HttpClientException as e:
            logger.error(f"HTTP请求异常: {e.message}")
            logger.error(f"异常详情: {e.details}")
        
    except HttpClientException as e:
        logger.error(f"HTTP请求异常: {e.message}")
        logger.error(f"异常详情: {e.details}")
    finally:
        # 关闭客户端
        client.close()


if __name__ == "__main__":
    basic_requests_example()
    request_builder_example()
    error_handling_example()